import {
	constantRouterMap,asyncRouterMap
} from '../router';
import {
	loginByPwd,
	logOut,
	getVerifyToken,
	getRoleInfo
} from "../api/auth";
import {
	hasPermission
} from '../utils/sift';
const auth = {
	state: {
		store_token: sessionStorage.getItem('lz-admin-token'),
		store_user_info: sessionStorage.getItem('lz-admin-uinfo'),
		store_name: '',
		store_phone: '',
		store_permissions: [],
		store_routers: constantRouterMap,
		store_add_routers: [],
	},
	mutations: {
		SET_STORE_TOKEN: (state, store_token) => {
			state.store_token = store_token;
		},
		SET_STORE_UINFO: (state, store_user_info) => {
			state.store_user_info = store_user_info;
		},
		SET_STORE_NAME: (state, store_name) => {
			state.store_name = store_name;
		},
		SET_STORE_PHONE: (state, store_phone) => {
			state.store_phone = store_phone;
		},
		SET_STORE_PERMISSIONS: (state, store_permissions) => {
			state.store_permissions = store_permissions;
		},
		SET_STORE_ROUTERS: (state, store_routers) => {
			state.store_add_routers = store_routers;
			state.store_routers = constantRouterMap.concat(store_routers);
		},
		SET_STORE_ADD_ROUTERS: (state, store_add_routers) => {
			state.store_add_routers = store_add_routers;
		},
	},
	actions: {
		Login({
			commit
		}, userInfo) {
			const username = userInfo.name.trim().replace(/\s+/g, "");
			return new Promise((resolve, reject) => {
				loginByPwd({
					username,
					password: userInfo.password,
					type: 2
				}).then(response => {
					if (response.data.code == 0) {
						const data = response.data.data;
						commit('SET_STORE_NAME', data.username);
						sessionStorage.setItem('lz-admin-uinfo', JSON.stringify(data));
						sessionStorage.setItem('lz-admin-token', data.id);
						commit('SET_STORE_TOKEN', data.id);
						commit('SET_STORE_UINFO', JSON.stringify(data));
					}
					resolve(response.data);
				}).catch(error => {
					reject(error);
				});
			});
		},
		Logout({
			commit
		}, id) {
			return new Promise((resolve, reject) => {
				logOut(id).then(res => {
					commit('SET_STORE_UINFO', '');
					commit('SET_STORE_TOKEN', '')
					commit('SET_STORE_NAME', '');
					commit('SET_STORE_PHONE', '');
					commit('SET_STORE_PERMISSIONS', []);
					commit('SET_STORE_ROUTERS', constantRouterMap);
					sessionStorage.removeItem('lz-admin-uinfo');
					sessionStorage.removeItem('lz-admin-token');

					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})

		},
		isLogin({
			commit
		}, id) {
			return new Promise((resolve, reject) => {
				commit('SET_STORE_TOKEN', id);
				getVerifyToken(id)
					.then(res => {
						resolve(res)
					}).catch(error => {
						reject(error)
					})
			})
		},
		/**
		 * ! 获取用户信息
		 */
		GetUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				let uId = JSON.parse(sessionStorage.getItem('lz-admin-uinfo')).role_id
				commit('SET_STORE_PHONE', JSON.parse(sessionStorage.getItem('lz-admin-uinfo')).phone);
				getRoleInfo(uId).then(res => {
					if (res.data.data.menu_ids.length > 0) {
						commit('SET_STORE_PERMISSIONS', res.data.data.menu_ids);
						resolve(Object.assign({}, {
							permissions: res.data.data.menu_ids
						}));
					} else {
						alert('您当前登录的账号没有任何系统操作权限,请联系管理员');
						reject(400);
					}


				}).catch(() => {
					reject(400)
				})
			})

		},
		FormatRoutes({
			commit
		}, data) {
			return new Promise((resolve) => {
				const permissions = data;
				
				const accessedRouters = asyncRouterMap.filter(v => {
					if (hasPermission(permissions, v)) {
						
						if (v.children && v.children.length > 0) {
							v.children = v.children.filter(child => {
								if (hasPermission(permissions, child)) {
									if (child.children && child.children.length > 0) {
										child.children = child.children.filter(_child => {
											if (hasPermission(permissions, _child)) {
												return _child
											}
											return false
										})
									}
									return child

								}
								return false
							})

						}
						return v
					}
					return false
				})
				accessedRouters.forEach(item => {
					if (!item.redirect && item.children && item.children.length) {
						item.redirect = item.children[0]['path'];
					}
				});
				commit('SET_STORE_ROUTERS', accessedRouters.concat([{
					path: '*', // 页面不存在的情况下会跳到404页面
					redirect: '/error',
					name: 'notFound',
				}, ]));
				resolve();
			})
		}
	}
}
export default auth;
